package org.crazyit.cloud.breaker;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandMetrics.HealthCounts;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

/**
 * 断路器开启测试
 * @author 杨恩雄
 *
 */
public class OpenTest {

	public static void main(String[] args) throws Exception {
		// 10秒内有10个请求，则符合第一个条件
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.metrics.rollingStats.timeInMilliseconds", 10000);
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.circuitBreaker.requestVolumeThreshold", 10);
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.circuitBreaker.errorThresholdPercentage", 50);
		for(int i = 0; i < 15; i++) {
			// 执行的命令全部都会超时
			MyCommand c = new MyCommand();
			c.execute();
			// 断路器打开后输出信息
			if(c.isCircuitBreakerOpen()) {
				System.out.println("断路器被打开，执行第 " + (i + 1) + " 个命令");
			}
		}
	}

	/**
	 * 模拟超时的命令
	 * @author 杨恩雄
	 *
	 */
	static class MyCommand extends HystrixCommand<String> {
		// 设置超时的时间为500毫秒
		public MyCommand() {
		    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
		            .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
		            		.withExecutionTimeoutInMilliseconds(500))
		    		);
		}

		protected String run() throws Exception {
			// 模拟处理超时
			Thread.sleep(800);
			return "";
		}

		@Override
		protected String getFallback() {
			return "";
		}
	}
}
